const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
const webpack = require('webpack');
const Webpackbar = require('webpackbar');
const port = 8081;

module.exports = {
  mode: 'development',
  entry: {
    bundle: [path.resolve(__dirname, 'src/index.js')],
  },
  output: {
    path: path.join(__dirname, 'build'),
    filename: 'js/[name].js',
    publicPath: '/',
  },
  // source-map会为每一个打包后的模块生成独立的sourcemap文件
  devtool: 'source-map',
  // 可以将公共的依赖模块提取到已有的入口 chunk 中，或者提取到一个新生成的 chunk。
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.(css|less)$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
            },
          },
          {
            loader: 'less-loader',
            // 当前需要加上options,否则报错
            options: {
              lessOptions: {
                modifyVars: {
                  'primary-color': '#1DA57A',
                  'link-color': '#1DA57A',
                  'border-radius-base': '2px',
                },
                javascriptEnabled: true,
              },
            },
          },
        ],
      },
      {
        test: /\.modules.(css|less)$/,
        exclude: /node_module/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: true,
            },
          },
          {
            loader: 'less-loader',
            // 当前需要加上options,否则报错
            options: {
              lessOptions: {
                modifyVars: {
                  'primary-color': '#1DA57A',
                  'link-color': '#1DA57A',
                  'border-radius-base': '2px',
                },
                javascriptEnabled: true,
              },
            },
          },
        ],
      },
      {
        test: /\.html$/,
        // 处理html中的img(负责引入img,从而能被url-loader进行处理)
        use: 'html-loader',
      },
      {
        test: /\.(png|jpeg|jpg|gif|pdf)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              // 图片小于8kb，就会被base64处理
              // 优点: 减少请求数量(减轻服务器压力)
              // 缺点：图片体积会更大(文件请求速度更慢)
              limit: 8 * 1024,
              // 打包后的路径和文件名称 [ext]扩展名
              name: 'img/[name].[ext]',
              // 打包后的文件指定访问路径前缀
              publicPath: '/',
            },
          },
        ],
      },
      // 主要用来处理阿里矢量图标库中的icon
      {
        test: /\.(woff|svg|eot|ttf)\??.*$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              name: 'fonts/[name].[ext]',
            },
          },
        ],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      /**
       * (node:10416) [DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH] DeprecationWarning: [hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)
       * (Use `node --trace-deprecation ...` to show where the warning was created)
       */
      filename: 'css/[name]_[chunkhash:6].css',
    }),
    new HtmlWebPackPlugin({
      template: './public/index.html',
      favicon: './public/HDK-ico.png',
      scriptLoading: 'blocking',
      // hash: true,
    }),
    new CleanWebpackPlugin(),
    new ESLintPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new Webpackbar({
      name: 'Ax',
      color: 'green',
      reporter: {
        done() {
          console.log(`http://localhost:${port}`);
        },
      },
    }),
    // new webpack.DefinePlugin({
    //   // 定义环境和变量
    //   'process.env': {
    //     NODE_ENV: 'development',
    //   },
    // }),
  ],

  devServer: {
    contentBase: path.resolve(__dirname, 'build'),
    inline: true,
    historyApiFallback: true,
    compress: true,
    hot: true,
    watchContentBase: true,
    quiet: true,
    stats: 'errors-only',
    port,
    proxy: {
      // 一旦devServer服务器接受到 /api开头的请求，就会把请求转发到另一个服务器
      '/api': {
        target: 'https://apis.juhe.cn/mobile/Example/query.php',
        pathRewrite: {
          '^/api': '',
        },
        changeOrigin: true,
        secure: false,
        ws: false,
      },
      '/sfz': {
        target: 'http://m.shenfenzheng.293.net/ids.php',
        pathRewrite: {
          '^/sfz': '',
        },
        changeOrigin: true,
        secure: false,
        ws: false,
      },

      '/hdk': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        secure: false,
        ws: false,
      },
    },
  },

  resolve: {
    // 配置解析模块路径别名：优点简写路径，缺点路径没有提示
    alias: {
      // 定义一个@，可在import引入时使用
      '@': path.resolve(__dirname, 'src'),
    },
    // 设置可以忽略不写的后缀
    extensions: ['.js', '.jsx'],
  },
};
